﻿#ifdef WIN32
//#include <Ws2tcpip.h>
//#include <winsock2.h>
//#pragma comment(lib,"Psapi.lib")
#else
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include "evutil.h"
#include "SL_net_inner.h"

#include <string.h>
#include "SL_net.h"

uint32_t  SLT_ip2num(const char* _ip)
{
    struct in_addr dst;
    memset(&dst, 0, sizeof(dst));
    if (1 != inet_pton(AF_INET, _ip, &(dst.s_addr))) {
        return 0;
    }
    return ntohl(dst.s_addr);
}
void  SLT_ip2str(uint32_t _localIp, std::string& _strip)
{
    struct in_addr s;
    s.s_addr = htonl(_localIp);
    char buf[16] = { 0 };
    if (NULL != inet_ntop(AF_INET, &s, buf, sizeof(buf)))
    {
        _strip = buf;
    }

}

std::string  SLT_ip2str(uint32_t _localIp)
{
	std::string strip;
    SLT_ip2str(_localIp, strip);
	return strip;
}

uint32_t SLT_ntohl(uint32_t _in) { return ntohl(_in); }
uint16_t SLT_ntohs(uint16_t _in) { return ntohs(_in); }
uint32_t SLT_htonl(uint32_t _in) { return htonl(_in); }
uint16_t SLT_htons(uint16_t _in) { return htons(_in); }

int SLT_getSocketInfoV4_inner(uint64_t _fd, uint16_t& _port)
{
    std::string tIp;
    return SLT_getSocketInfoV4_inner(_fd, tIp, _port);
}
int SLT_getSocketInfoV4_inner(uint64_t _fd, std::string& _ip, uint16_t& _port)
{
    // 获取绑定的本地地址和端口号
    struct sockaddr_storage ss;
    ev_socklen_t socklen = sizeof(ss);
    if (getsockname(_fd, (struct sockaddr*)&ss, &socklen) == -1) {
        //printf("Couldn't get socket name: %s\n", strerror(errno));
        return -1;
    }

    // 打印绑定的IP地址和端口号
    char addrbuf[128];
    if (ss.ss_family == AF_INET) {
        struct sockaddr_in* sin = (struct sockaddr_in*)&ss;
        _ip = evutil_inet_ntop(AF_INET, &sin->sin_addr, addrbuf, sizeof(addrbuf));
        _port = ntohs(sin->sin_port);
    }
    /*else if (ss.ss_family == AF_INET6) {
        struct sockaddr_in6* sin6 = (struct sockaddr_in6*)&ss;
        addr = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, addrbuf, sizeof(addrbuf));
        port = ntohs(sin6->sin6_port);
    }*/
    else {
        //printf("Invalid address family\n");
        return -2;
    }
    //printf("Listening on %s:%d\n", addr, port);
    return 0;
}

